/*
* @(#)DmsDocFolderPickerTag.java
*
* Copyright (c) 2004 DCIVision Ltd
* All rights reserved.
*
* This software is the confidential and proprietary information of DCIVision
* Ltd ("Confidential Information").  You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the license
* agreement you entered into with DCIVision Ltd.
 */

package com.dcivision.dms.taglib;

import java.sql.Connection;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsRoot;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.core.RootRetrievalManager;
import com.dcivision.dms.dao.DmsDocumentDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.PermissionManager;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.taglib.html.FormTag;

/**
  <p>Class Name:    LocationPathTag.java    </p>
  <p>Description:   This tag is the layout the document location

  <p>Modification in "dms.tld"<br>
  <pre>
     [FROM]
     &lt;tagclass&gt;javax.servlet.jsp.tagxt.BodyTagSupport&lt;/tagclass&gt;
     [TO]
     &lt;tagclass&gt;com.dcivision.dms.taglib.layout.LocationPathTag&lt;/tagclass&gt;

     [ADDED]
     &lt;attribute&gt;
     &lt;name&gt;parentID&lt;/name&gt;
     &lt;required&gt;true&lt;/required&gt;
     &lt;rtexprvalue&gt;true&lt;/rtexprvalue&gt;
     &lt;/attribute&gt;
     &lt;attribute&gt;
     &lt;name&gt;rootID&lt;/name&gt;
     &lt;required&gt;true&lt;/required&gt;
     &lt;rtexprvalue&gt;true&lt;/rtexprvalue&gt;
     &lt;/attribute&gt;
     &lt;attribute&gt;
     &lt;name&gt;permission&lt;/name&gt;
     &lt;required&gt;true&lt;/required&gt;
     &lt;rtexprvalue&gt;true&lt;/rtexprvalue&gt;
     &lt;/attribute&gt;
     &lt;attribute&gt;
     &lt;name&gt;rootDocument&lt;/name&gt;
     &lt;required&gt;true&lt;/required&gt;
     &lt;rtexprvalue&gt;true&lt;/rtexprvalue&gt;
     &lt;/attribute&gt;
  </pre>
  </p>

  <p>USAGE:</p>
  <p>The following example shows how to show the customized page title using pass in String array</p>
  <p><code>&lt;dms:locationPath/&gt; parentID='ParentID'</strong> <strong>rootID='RootID'</strong></p>
  <p><strong> permission='PermissionStr'</strong> <strong>rootDocument='RootDocument'</strong> &gt;</code></p>

 * @author           Zoe Shum
 * @company          DCIVision Limited
 * @creation date    08/08/2003
 * @version          $Revision: 1.4.2.4 $
 */

public class DmsDocFolderPickerTag extends BodyTagSupport {

  public static final String REVISION = "$Revision: 1.4.2.4 $";


  int iscreenSize = -1;
  int idefaultLength ;
  int isize640 = SystemParameterFactory.getSystemParameterInteger(SystemParameterConstant.DMS_MAX_WORDS_OF_TITLE_BY_SCREEN_WIDTH_640).intValue();
  int isize800 = SystemParameterFactory.getSystemParameterInteger(SystemParameterConstant.DMS_MAX_WORDS_OF_TITLE_BY_SCREEN_WIDTH_800).intValue();
  int isize1024 = SystemParameterFactory.getSystemParameterInteger(SystemParameterConstant.DMS_MAX_WORDS_OF_TITLE_BY_SCREEN_WIDTH_1024).intValue();
  int isize1152 = SystemParameterFactory.getSystemParameterInteger(SystemParameterConstant.DMS_MAX_WORDS_OF_TITLE_BY_SCREEN_WIDTH_1152).intValue();
  int isize1280 = SystemParameterFactory.getSystemParameterInteger(SystemParameterConstant.DMS_MAX_WORDS_OF_TITLE_BY_SCREEN_WIDTH_1280).intValue();
  int isize1281 = SystemParameterFactory.getSystemParameterInteger(SystemParameterConstant.DMS_MAX_WORDS_OF_TITLE_BY_SCREEN_WIDTH_1281).intValue();

  private Integer sParentID;
  private Integer sRootID;
  private String sPermission=null;
  private DmsDocument rootDocument=null;
  private boolean bOnClick = true;
  public static final String FILE_SEPARATOR = "\\";
  private boolean bShowIndexFlag = true;
  private int limitLength = -1;
  private String indexFlag="showIndexFlag";
  private boolean bShowAllPath = true;
  
  private static final Log log = LogFactory.getLog(DmsDocFolderPickerTag.class);
  /**
   * Constructor
   */
  public int getDefaultValue() {
        this.iscreenSize = TextUtility.parseInteger(this.pageContext.getSession().getAttribute(GlobalConstant.CLIENT_SCREEN_WIDTH_KEY).toString() );

        if (iscreenSize <= 640) {
                idefaultLength = isize640;
        } else if(iscreenSize <= 800 && iscreenSize >640 ) {
                idefaultLength = isize800;
        } else if(iscreenSize <= 1024 && iscreenSize >800 ) {
                idefaultLength = isize1024;
        } else if(iscreenSize <= 1152 && iscreenSize >1024 ) {
                idefaultLength = isize1152;
        } else if(iscreenSize <= 1280 && iscreenSize >1152 ) {
                idefaultLength = isize1280;
        } else {
                idefaultLength = isize1281;
        }
        return idefaultLength;
  }

  public void setShowAllPath(boolean bShowAllPath){
    this.bShowAllPath = bShowAllPath;
  }

  public boolean getShowAllPath() {
    return this.bShowAllPath;
  }

  public void setShowIndexFlag(boolean indexFlag){
    this.bShowIndexFlag = indexFlag;
  }

  public boolean getShowIndexFlag() {
    return this.bShowIndexFlag;
  }

  public void setIndexFlag(String indexFlag) {
    this.indexFlag = indexFlag;
  }

  public String getIndexFlag() {
    return this.indexFlag;
  }

  public DmsDocFolderPickerTag() {
    super();
  }

  public Integer getParentID() {
    return this.sParentID;
  }

  public void setParentID(Integer sParentID) {
    this.sParentID = sParentID;
  }

  public Integer getRootID() {
    return this.sRootID;
  }

  public void setPermission(String permission){
    this.sPermission = permission;
  }

  public String getPermission(){
    return this.sPermission;
  }

  public void setRootDocument(DmsDocument rootDoc){
    this.rootDocument = rootDoc;
  }

  public DmsDocument getRootDocument(){
    return this.rootDocument;
  }

  public void setRootID(Integer sRootID) {
    this.sRootID = sRootID;
  }

  public boolean getOnClick(){
    return this.bOnClick;
  }

  public void setOnClick(boolean onClick){
    this.bOnClick = onClick;
  }

  public int getLimitLength() {
     return (this.limitLength);
  }

  public void setLimitLength(int limitLength) {
        this.limitLength = limitLength;
  }

  public int doStartTag() throws JspException {
     if (sParentID == null) {
       throw new JspTagException("LocationPathTag: no header String defined");
     }
     try {
       pageContext.getOut().print(this.src());
       return(SKIP_BODY);
     } catch (Exception e) {
       log.error(e, e);
       throw new JspException(e);
     }
   }

   public int doEndTag() throws JspException {
     return EVAL_PAGE;
  }

  protected String src() throws javax.servlet.jsp.JspException {

    limitLength = getDefaultValue();
    FormTag formTag = (FormTag)BodyTagSupport.findAncestorWithClass(this, FormTag.class);

    SessionContainer sessionContainer = (SessionContainer)this.pageContext.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY);
    Connection conn = (Connection)pageContext.getRequest().getAttribute(GlobalConstant.DB_KEY);
    String contextPath = (String)this.pageContext.getServletContext().getAttribute(GlobalConstant.CONTEXT_PATH_KEY);
    DmsDocumentDAObject dmsDocmentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    RootRetrievalManager rootRetrievalManager = new RootRetrievalManager(sessionContainer, conn);
    PermissionManager permissionManager = sessionContainer.getPermissionManager();

    StringBuffer buffer = new StringBuffer();
    String path="";
    try {
      if (bShowAllPath) {
      	//is root folder
      	if (sParentID.intValue()==0){
          List publicRootList = rootRetrievalManager.getAllAccessibleRootsList();
          DmsRoot folderRoot = (DmsRoot)publicRootList.get(0);
          DmsDocument folderRootDocument = docRetrievalManager.getRootFolderByRootID(folderRoot.getID());
          
          if (DmsOperationConstant.DMS_PERSONAL_ROOT.equals(rootDocument.getDocumentName())){
            //For Personal Folder
            String name = folderRootDocument.getDocumentName();
            if (rootDocument.getOwnerID().intValue() != sessionContainer.getUserRecordID().intValue()){
              name = UserInfoFactory.getUserFullName(folderRootDocument.getOwnerID()) + " " +folderRootDocument.getDocumentName();
              buffer.insert(0, name);
            }else{
              if (!bOnClick) {
                buffer.insert(0, name);
              } else {
                if (GlobalConstant.RECORD_STATUS_ACTIVE.equals(folderRootDocument.getRecordStatus())){
                  String url = contextPath + "/dms/ListDmsDocument.do?rootID=" + sRootID + "&parentID=" + sParentID +  "&curFunctionCode=" + SystemFunctionConstant.DMS_PERSONAL_FOLDER + "&sortAttribute=";
                  buffer.insert(0, " <a href=\"javascript://\" onclick=\"return checkWindowForAction('" + url + "');\"/>" + name + "</a>");
                }
                else {
                  buffer.insert(0, name);
                }
              }
            }
          } else {
            //For Public Folder
            if  (sPermission.indexOf("R")>=0) {
              if (!bOnClick) {
                buffer.insert(0, rootDocument.getDocumentName());
              } else {
                if (GlobalConstant.RECORD_STATUS_ACTIVE.equals(rootDocument.getRecordStatus())) {
                  String url = contextPath + "/dms/ListDmsPublicDocument.do?rootID=" + sRootID + "&parentID=" + sParentID +  "&curFunctionCode=" + SystemFunctionConstant.DMS_PUBLIC_FOLDER +"&sortAttribute=";
                  buffer.insert(0, " <a href=\"javascript://\" onclick=\"return checkWindowForAction('" + url + "');\"/>" + rootDocument.getDocumentName() + "</a>");
                } else {
                  buffer.insert(0, rootDocument.getDocumentName());
                }
              }
            } else {
              buffer.insert(0, rootDocument.getDocumentName());
            }
          }
          buffer.insert(0, FILE_SEPARATOR);
          sParentID = folderRootDocument.getParentID();
        }
      	
      	while (sParentID.intValue()!=0){          
          DmsDocument doc = docRetrievalManager.getDocument(sParentID);
//          DmsDocument documentRoot = docRetrievalManager.getRootFolderByRootID(((DmsDocument) doc).getRootID());
//          String permission = (String) permissionManager.getPermission(GlobalConstant.OBJECT_TYPE_DOCUMENT, documentRoot.getID());

          if (rootDocument==null) {
            buffer.insert(0, GlobalConstant.EMPTY_FIELD);
            break;
          }
          if (DmsOperationConstant.DMS_PERSONAL_ROOT.equals(rootDocument.getDocumentName())){
            //For Personal Folder
            String name = doc.getDocumentName();
            if (rootDocument.getOwnerID().intValue() != sessionContainer.getUserRecordID().intValue()){
              name = UserInfoFactory.getUserFullName(doc.getOwnerID()) + " " +doc.getDocumentName();
              buffer.insert(0, name);
            }else{
              if (!bOnClick) {
                buffer.insert(0, name);
              } else {
                if (GlobalConstant.RECORD_STATUS_ACTIVE.equals(doc.getRecordStatus())){
                  String url = contextPath + "/dms/ListDmsDocument.do?rootID=" + sRootID + "&parentID=" + sParentID +  "&curFunctionCode=" + SystemFunctionConstant.DMS_PERSONAL_FOLDER + "&sortAttribute=";
                  buffer.insert(0, " <a href=\"javascript://\" onclick=\"return checkWindowForAction('" + url + "');\"/>" + name + "</a>");
                }
                else {
                  buffer.insert(0, name);
                }
              }
            }
          } else {
            //For Public Folder
            if  (sPermission.indexOf("R")>=0) {
              if (!bOnClick) {
                buffer.insert(0, doc.getDocumentName());
              } else {
                if (GlobalConstant.RECORD_STATUS_ACTIVE.equals(doc.getRecordStatus())) {
                  String url = contextPath + "/dms/ListDmsPublicDocument.do?rootID=" + sRootID + "&parentID=" + sParentID +  "&curFunctionCode=" + SystemFunctionConstant.DMS_PUBLIC_FOLDER +"&sortAttribute=";
                  buffer.insert(0, " <a href=\"javascript://\" onclick=\"return checkWindowForAction('" + url + "');\"/>" + doc.getDocumentName() + "</a>");
                } else {
                  buffer.insert(0, doc.getDocumentName());
                }
              }
            } else {
              buffer.insert(0, doc.getDocumentName());
            }
          }
          buffer.insert(0, FILE_SEPARATOR);
          sParentID = doc.getParentID();
        }        	
      	
        //

        path = buffer.toString();
        if (path.length() > 0) {
          path = path.substring(1);
        }
      } else {
        DmsDocument doc = docRetrievalManager.getDocument(sParentID);
        String name = docRetrievalManager.getLocationPath(sParentID);

        if (name.length() > this.limitLength ) {
          name = name.substring(0,this.limitLength).replaceAll(" ", "&nbsp;")+"...";
        }

        if (DmsOperationConstant.DMS_PERSONAL_ROOT.equals(rootDocument.getDocumentName())) {
          //For Personal Folder
          if (rootDocument.getOwnerID().intValue() != sessionContainer.getUserRecordID().intValue()) {
            if(docRetrievalManager.getLocationPath(sParentID).length() > this.limitLength ) {
              name = docRetrievalManager.getLocationPath(sParentID).substring(0,this.limitLength).replaceAll(" ", "&nbsp;")+"...";
            }
            buffer.insert(0, name);
          } else {
            if (!bOnClick) {
            buffer.insert(0, name);
            } else {
              if (GlobalConstant.RECORD_STATUS_ACTIVE.equals(doc.getRecordStatus())) {
                String url = contextPath + "/dms/ListDmsDocument.do?rootID=" + sRootID + "&parentID=" + sParentID +  "&curFunctionCode=" + SystemFunctionConstant.DMS_PERSONAL_FOLDER + "&sortAttribute=";
                if (bShowIndexFlag) {
                  buffer.insert(0, " <a href=\"javascript://\" onclick=\"return checkWindowForAction('" + url + "');\" " +
                    " onmouseover=\"if (document." + formTag.getBeanName() + "." + indexFlag + " && document." + formTag.getBeanName() + "." + indexFlag + ".checked) { return getDocumentInfo('" +TextUtility.escapeJSString(docRetrievalManager.getLocationPath(sParentID)) + "'); } else { return(false); }\" onmouseout=\"return nd();\">" + name + "</a>");
                } else {
                  buffer.insert(0, "  <a href=\"javascript://\" onclick=\"return checkWindowForAction('" + url + "');\" "+
                    " onmouseover=\"return(false);\">" + name + "</font></a>");
                }
              } else {
                buffer.insert(0, name);
              }
            }
          }
        } else {
          //For Public Folder
          if  (sPermission.indexOf("R")>=0) {
            if (!bOnClick) {
              buffer.insert(0, name);
            } else {
              if (GlobalConstant.RECORD_STATUS_ACTIVE.equals(doc.getRecordStatus())) {
                String url = contextPath + "/dms/ListDmsPublicDocument.do?rootID=" + sRootID + "&parentID=" + sParentID +  "&curFunctionCode=" + SystemFunctionConstant.DMS_PUBLIC_FOLDER +"&sortAttribute=";
                if (bShowIndexFlag) {
                   buffer.insert(0, " <a href=\"javascript://\" onclick=\"return checkWindowForAction('" + url + "');\" " +
                     " onmouseover=\"if (document." + formTag.getBeanName() + "." + indexFlag + " && document." + formTag.getBeanName() + "." + indexFlag + ".checked) { return getDocumentInfo('" +TextUtility.escapeJSString(docRetrievalManager.getLocationPath(sParentID)) + "'); } else { return(false); }\" onmouseout=\"return nd();\">" + name + "</a>");
                } else {
                   buffer.insert(0, "  <a href=\"javascript://\" onclick=\"return checkWindowForAction('" + url + "');\" "+
                     " onmouseover=\"return(false);\">" + name + "</font></a>");
                }
                //buffer.insert(0, " <a href=\"javascript://\" onclick=\"return checkWindowForAction('" + url + "');\"/>" + name + "</a>");
              } else {
                buffer.insert(0, name);
              }
            }
          } else {
            buffer.insert(0, name);
          }
        }
        buffer.insert(0, FILE_SEPARATOR);

        path = buffer.toString();
        if (path.length() > 0) {
          path = path.substring(1);
        }
        String url = contextPath + "/dms/ListDmsDocument.do?rootID=" + sRootID + "&parentID=" + sParentID +  "&curFunctionCode=" + SystemFunctionConstant.DMS_PERSONAL_FOLDER + "&sortAttribute=";
        if (path.indexOf("<a href")<0 && path.length() > this.limitLength) {
           path = " <a href=\"javascript://\" onmouseover=\"if (document." + formTag.getBeanName() + "." + indexFlag + " && document." + formTag.getBeanName() + "." + indexFlag + ".checked) { return getDocumentInfo('" +TextUtility.escapeJSString(docRetrievalManager.getLocationPath(sParentID)) + "'); } else { return(false); }\" onmouseout=\"return nd();\">" + path.substring(0,this.limitLength).replaceAll(" ", "&nbsp;")+"..." + "</a>";
        }
      }
    } catch (ApplicationException appEx) {
      throw new JspException(appEx);
    }

    return path;
  }

  public void release() {
    super.release();
    sParentID = null;
  }
}